Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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?

share|improve this question

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.