Search code examples
reactjsantd

How to validate Only working emails & if working email is not input by user show him an error in react js antdesing


Here is form input field

  <Form.Item
                    className="form-elemnt"
                    name="email"
                    label="Email"
                    rules={[
                      {
                        type: 'email',
                        message: 'The input is not valid E-mail!',
                      },
                      {
                        required: true,
                        message: "Please input your Email",
                      },
                     
                    ]}
                  >
                    <Input
                      size="large"
                      type="email"
                      onChange={(e) => {
                        handleEmail(e)
                      }}
                      value={email}
                    />
                  </Form.Item>

here is the logic to exclude @gmail, @yahoo @outlook @hotmail. Only accept working email like johndoe@stack.com etc

const handleEmail=(e)=>{
    const value = e.target.value
    let domain = value.substring(value.lastIndexOf("@"))
    if(domain == "@gmail.com" || domain == "@yahoo.com" || domain == "@hotmail.com" || domain == "@outlook.com"){

    }
    else{
      setEmail(value)
    }
  }

I want that if user enter email like @gmail @yahoo @outlook @hotmail there should an error message is shown below the input field that please enter working email only


Solution

  • You can use regex in your handleEmail for excluding gmail, yahoo and hotmail.

    const handleEmail=(e)=>{
      const value = e.target.value
      if (/^([\w.-]+)@(\[(\d{1,3}\.){3}|(?!hotmail|gmail|yahoo)(([a-zA-Z\d-]+\.)+))([a-zA-Z]{2,4}|\d{1,3})(\]?)$/.test(value)){
        // Code...    
      }
      else{
        setEmail(value)
      }
    }