简体   繁体   中英

How to check if the user entered input in input field has the string in format '10h' or '10m' using react and javascript?

i have an input field. to this input field is the duration field.

so user can enter time liek below,

10h 10m

200h 40m and so on.

now i have to display a message if the user entered duration is invalid. so when user enters say 10 or 200 or 40 then i should display message invalid.

below is my code,

function Parent() {
    return (
        <input 
            ref={inputRef}
        />
        <button onClick= {handleClick}>button</button> //on clicking this button should validate input field
    );
 }

how can i do it in javascript ?

could someone help me with this. thanks.

    <input 
        ref={inputRef}
        pattern="/^[0-9]+(h|m)$/"
    />

You could use regular expressions that way you could even define capture groups that extract your hours and minutes.

See documentation for RegExp on mdn: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM