Custom Validation - if statement

117 Views Asked by At

A newbie here. just wanted to ask what is the meaning of the code below.

if((control.value as string).indexOf(' ') >=0)

I was doing some self-study and I could not understand it. Appreciate if you give a hand to explain it at a very low level.

here the full code;

export class UsernameValidators {
    static connotContainSpace( control: AbstractControl) : ValidationErrors | null {
// this is the part when the validation is stated

    if((control.value as string).indexOf(' ') >=0)
     return { cannotContainSpace: true }

    return null; 
}
2

There are 2 best solutions below

2
vikas336 On

I am trying to explain you using a simple example:

control.value = "This is stackoverflow";

.indexOf(' ') will find the first index number for space substring in control.value

like in our example first space is present in index number 4, which is greater than zero , then if statement will execute.

1
CostaIvo On
if((control.value as string).indexOf(' ') >=0)

Lets breakdown the above code statement one at a time.

  • control.value as string

The above code converts the content of control.value as a string datatype

  • (control.value as string).indexOf(' ')

indexOf is a method available on string datatype. It returns the index of the first occurrence of the string/character specified in the parameter. If the string/character is not found then it will return -1 else any value above zero or zero itself.

In the above example the character is ' ' i.e. space character.

  • if((control.value as string).indexOf(' ') >=0)

The if statement checks if the value returned is greater than or equal to zero. if the value is true it implies that the character space was found in the string value of control.value