user3064132
user3064132

Reputation: 113

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

Upvotes: 0

Views: 38

Answers (3)

Mudassir Hasan
Mudassir Hasan

Reputation: 28771

Below $("#uxPromoCode").val() will give you value contain in textbox and indexOf() function checks whether string ABC is present anywhere in textbox value.

if($("#uxPromoCode").val().indexOf("ABC") != -1 ){ 
    Dialog.msg({
        title: Message.dlg.title4, 
        msg: 'TRUE CODE', 
    });
}else{
    Dialog.msg({
        title: Message.dlg.title4, 
        msg: 'FALSE CODE', 
    });
}

To check for start of string is ABC use match regex function . The character ^ indicates check at start of string contained in textbox

if($("#uxPromoCode").val().match("^ABC")){ 
    Dialog.msg({
        title: Message.dlg.title4, 
        msg: 'TRUE CODE', 
    });
}else{
    Dialog.msg({
        title: Message.dlg.title4, 
        msg: 'FALSE CODE', 
    });
}

Upvotes: 2

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

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"/>

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26278

Use JS Regular Expression like:

var haystack = 'hello world';
var needle = 'he';

if (haystack.indexOf(needle) == 0) {
  // your code if string starts with 'he'
} 

Regex Reference

Upvotes: 0

Related Questions