Example to validate input fields only numbers, alphabets, phone etc.

  • In the following example, we are observing how to validate a value entered into an input field.

    import React from 'react'

    const App = () => {
      const [value, setValue] = React.useState('');

      // Validation functions
      const onlyNumbers = value => /^[0-9]*$/.test(value);
      const onlyAlphabets = value => /^[a-zA-Z]*$/.test(value);
      const phoneNumber = value => /^\d{0,10}$/.test(value);

      return (<>
        <input
          type="text"
          onChange={(event) => {
            const newValue = event.target.value;
            if (phoneNumber(newValue)) {
              setValue(newValue);
            }
          }}
          value={value}
        />
      </>)
    }

    export default App



No comments:

Post a Comment

PHP & Laravel — Zero to Hero Episode 17: Controllers — Organizing Your Application Logic the Laravel Way

What Are We Doing in This Post? In Episode 16 we defined routes using closures — anonymous functions directly inside routes/web.php . That w...