user3064132 user3064132 - 2 months ago 7
jQuery Question

How can I validate text from given word

How can i check if text begin with ABCxx or ABCxxxx return true . tried using contains or attribue value but all return true

<input id="uxPromoCode" name="uxPromoCode" value="" class="form-input">

if("#uxPromoCode:contains('ABC')" ){ // $("#uxPromoCode[value^='ABC']")
Dialog.msg({
title: Message.dlg.title4,
msg: 'TRUE CODE',
});
}else{
Dialog.msg({
title: Message.dlg.title4,
msg: 'FALSE CODE',
});
}


Example:

ABCJ8 -true
ABCJ89K -true
ABCKL -true
KLHXN -false
C7HKLOJ -false

Answer

You can use .match here with regex. The way you are currently implementing it is kind of CSS attribute and it results in true even if it finds AB at beginning. Below is the snippet how you can use .match

$('.validate').on('click', function() {
  if ($("#uxPromoCode").val().match('^ABC')){
    /*Dialog.msg({
        title: Message.dlg.title4, 
        msg: 'TRUE CODE', 
    });*/
    console.log(true);
  } else {
    console.log(false);
    /*Dialog.msg({
        title: Message.dlg.title4, 
        msg: 'FALSE CODE', 
    });*/
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="uxPromoCode" name="uxPromoCode" value="" class="form-input"/>
<input type="button" value="Validate" class="validate"/>

Comments