1

I am trying to insert a validation into my Angular 9 app which doesn't let a user insert loads of spaces instead of a text into a form.

Currently, I have the below code but it doesn't let for any space. I would like the user to be able to insert a space but not just all spaces as I need useful data in my database. This example is an enquiry form for my website. I have the below code with the custom empty space validator but as mentioned it doesn't let me insert any space. The aim is here to not allow users enter content such as 20 empty spaces or random repeated letters such as 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr'.

Here is the code snippet I have but I think it will need to be changed altogether:

import { AbstractControl, ValidationErrors } from '@angular/forms';
    export function NoWhitespaceValidator(control: AbstractControl) : ValidationErrors | null {
        if((control.value as string).indexOf(' ') >= 0) {
            return {cannotContainSpace: true}
        }
    return null;
}

Only solutions that I seem to find are just validators that don't allow a single space.

3 Answers 3

1

try

if ((control.value as string).includes(' ')  && (control.value as string).indexOf(' ') != 0) {
return {cannotContainSpace: true}
}
Sign up to request clarification or add additional context in comments.

7 Comments

try inside of the first if statment putting if( !(control.value as string).includes(" ")){
btw there is two spaces in that quote
Hi, I'm trying to find a way that a space after a single word is permitted but several spaces are not permitted. At the moment it doesn't allow a single space after a single word. Hope that makes sense. So pretty much how to ensure a user does not insert blank spaces into a database through the form
do you mean that after the first word there can be no more spaces?
|
0

We could even improve this RegExp for multiline validation as follows:

const pattern = new RegExp('^(?!.*([A-Za-z0-9])\1{3})(?! +$)[A-Za-z -]+$','m'); 

Validators.pattern(pattern);  //form control

Comments

0

As per VeKri's help, I have done this in regular expressions way and the below are my results:

Validators.pattern('^(?!.*([A-Za-z0-9])\\1{3})(?! +$)[A-Za-z -]+$')

The first part makes sure that the same characters are not repeated more than 3 times in order to avoid input such as 'ddddddddddddd', while the second part (second pair of brackets) does not allow input of solely spaces to be inserted.

It was very useful to use a regular expressions tester such as https://regex101.com/ in order to play about with the expression.

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.