3

I am trying to migrate my demo project to Angular as I am learning the same. But I faced a dilemma as whether to opt for a razor view form validation while adding or rather updating some info on the client side or to opt for Angular JS ?

So In Angular How would I achieve the same. Suppose I have a _AddDetails.cshtml partial view :

@model MvcApplication4.Models.Student
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend><strong>Create a record</strong></legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DepartmentID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DepartmentID)
            @Html.ValidationMessageFor(model => model.DepartmentID)
        </div>

        <p>
            <input type="submit" class="createDetails" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

and in MVC I have opted for FluentValidation of the model.

The model looks like :

[FluentValidation.Attributes.Validator(typeof(StudentViewModelValidator))]
public class Student
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StudentId { get; set; }
    public String LastName { get; set; }
    public String FirstName { get; set; }
    public String UserName { get; set; }
    public String Password { get; set; }

    [ForeignKey("Department")]
    public int DepartmentID { get; set; }

    //Department Navigational Property
    public Department Department { get; set; }
}

And the validation looks like :

public class StudentViewModelValidator : AbstractValidator<Student>
{
    public StudentViewModelValidator()
    {
        RuleFor(m => m.FirstName)
            .NotEmpty().WithMessage("First Name is required.")
            .Matches(@"^\D*$").WithMessage("Numbers are not allowed in First Name");
        RuleFor(m => m.LastName)
            .NotEmpty().WithMessage("Last Name is required.")
            .Matches(@"^\D*$").WithMessage("Numbers are not allowed in Last Name");
        RuleFor(m => m.UserName)
            .NotEmpty().WithMessage("User Name is required.")
            .Matches(@"^[a-zA-Z0-9\.\$]*$").WithMessage("Only . and $ are allowed special characters in a user name");
        RuleFor(m => m.Password)
            .NotEmpty().WithMessage("Password is required.")
            .Length(4, 10).WithMessage("Password should be 4 to 10 characters long")
            .Matches(@"^(?=(\D*\d){2,})(?=([^a-zA-Z]*[a-zA-Z]))(?=[^\.\$\~\&]*[\.\$\~\&]).*").WithMessage("Password should contain at least 2 digits,a letter and at least a special character in it");

    }

But in angular if I re-build my view instead of this razor template how would I achieve these sort of complex regex validations ? I know I have something like

ng-required
ng-minlength
ng-maxlength

But how would I achieve like the above razor validations?

2 Answers 2

1

Use can use ng-pattern for regex

 <script>
      angular.module('ngPatternExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.regex = '\\d+';
        }]);
    </script>
    <div ng-controller="ExampleController">
      <form name="form">
        <label for="regex">Set a pattern (regex string): </label>
        <input type="text" ng-model="regex" id="regex" />
        <br>
        <label for="input">This input is restricted by the current pattern:     </label>
        <input type="text" ng-model="model" id="input" name="input"         ng-pattern="regex" /><br>
    <hr>
    input valid? = <code>{{form.input.$valid}}</code><br>
    model = <code>{{model}}</code>
      </form>
    </div>

Reference : https://docs.angularjs.org/api/ng/directive/ngPattern

Sign up to request clarification or add additional context in comments.

Comments

0

I implemented the validation in my MVC project that uses angular, so I used the ng-pattern, I had a problem trying to include some special chars as valid for the user name: "@", "_" and "-".

The only way I succeed was to add them as separate repeatable chars at the end of my pattern:

ng-pattern="/^[a-zA-Z0-9.]*[@('_')]*[@('-')]*[@('@')]*$/"

I hope this works for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.