0

I am working on Angular 5 and I have a form with a field username. I want to integrate a custom validation for minimum character length and avoid blank space.

<input type="text" class="form-control " id="account-details-username" placeholder="" formControlName="username" >
        <div *ngIf="form.get('accountDetails.username').touched && form.get('accountDetails.username').invalid" class="alert alert-danger">
          <div *ngIf="form.get('accountDetails.username').errors.required">Username is required.</div>
          <div *ngIf="form.get('accountDetails.username').errors.minimumSix">Username must contain at least 6 characters</div>
          <div *ngIf="form.get('accountDetails.username').errors.blankSpace">Username does not contain blank space.</div>
        </div>

I tried to create a custom method for that. But invoking the first condition only.

test(control: any) {
console.log(control.value);
let minimumSix = new RegExp("^[a-zA-Z0-9!@#$%^&*]{6,}");

if (!minimumSix.test(control.value)) {
  return { 'minimumSix': true };
}

if(control.value.match("^\\s+$")) {
  console.log("blank");
  return { 'blankSpace': true };
}

return null;
}

Not checking the blank space validation.

3
  • Maybe it can be solved by adding ng-trim="false" to input? Commented May 29, 2018 at 8:41
  • Do I get you right? Your problem is, that the "blank-validation" isn't working at all? Commented May 29, 2018 at 9:35
  • Yes @DiabolicWords Commented May 29, 2018 at 11:04

1 Answer 1

1

I'd suggest the following solution, when it comes to blanks.

const blankSpace = /^\S*$/;

if (!blankSpace.test(control.value)) {
    console.log("blank");
    return { 'blankSpace': true };    
}

So your full method should look like this:

test(control: any) {
    const minimumSix = new RegExp("^[a-zA-Z0-9!@#$%^&*]{6,}");
    const blankSpace = /^\S*$/;

    if (!minimumSix.test(control.value)) {
      return { 'minimumSix': true };
    }

    if (!blankSpace.test(control.value)) {
        console.log("blank");
        return { 'blankSpace': true };    
    }

    return null;
}
Sign up to request clarification or add additional context in comments.

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.