Validate alpha numeric on a field in catalog item

SD29
Tera Expert

Hi Folks,

I am trying to validate an alpha-numeric field of length 10 in a catalog item. It's giving me an error even though I have used the alpha-numeric. I am doing this by onChange client script.

function onChange(control, oldValue, newValue, isLoading) {

    if (isLoading || newValue == '') {

          return;

    }

  g_form.hideFieldMsg('sap_customer_number');

  var patt =new RegExp("^[a-zA-Z0-9]*$");

  if (!patt.test(newValue)||patt.length !="10")

  g_form.showFieldMsg('sap_customer_number','Invalid input','error');

}

Here are the results when I used this script:

Screen Shot 2017-03-03 at 12.02.31 PM.png

Thanks in Advance,

SD

1 ACCEPTED SOLUTION

That's strange, since it worked in my developer instance.   Here's the full script:



function onChange(control, oldValue, newValue, isLoading) {


  if (isLoading || newValue == '') {


            return;


  }


 


  g_form.hideFieldMsg('sap_customer_number');


  var patt = new RegExp("^[a-zA-Z0-9]*$");


  if (!patt.test(newValue + '') || newValue.length !="10")


            g_form.showFieldMsg('sap_customer_number','Invalid input','error');


}




The only other thing I did was force newValue to a string in line 8.


View solution in original post

12 REPLIES 12

I know, I am late to the party, but still.

The pattern drjohnchun advises is correct.

The original pattern

^[a-zA-Z0-9]*$

Is wrong and dangerous. Note that * means "zero to any number of times". In other words, the empty string matches this pattern. Patterns like * or . and especially .* should be avoided because often, much more matches than needed.

Compare to the correct one:

^[a-zA-Z0-9]{10}$

Here, exactly 10 characters are required (as snow123@ verifies in a later step).

If people copy this pattern without the if statement, things may go wrong.

I always test my regexes using tools like https://regex101.com/ or https://www.regexbuddy.com/.

Sorry for the nitpicking.

 

Best
Daniel


If this answer was helpful, I would appreciate if you marked it as such - thanks!

Best
Daniel

Vespertinus
Tera Expert

Hello all, thx for useful discussion. Could reuse the regex for my use cases.


One question left from my side, how to prevent to catlog item then to be ordered? This simply shows the validation error, but catalog item still can be submitted...


Thx and br


Vesp


You'll need to create an onSubmit function with the same logic, in addition to the onChange script that displays the warning.   In the onSubmit function, return 'false' to prevent the item from being submitted.