-->

  • How to validate emoji in input field by using emoji regex formik in Reactjs ?

     

    How to validate emoji in input field by using emoji regex formik in Reactjs ?



    Today in this blog, we will aware about How to validate emoji in input field by using emoji regex formik. So, without wasting any time lets do it but lets recap what is exactly React js. 



    React


    Certainly! ReactJS is a JavaScript library developed by Facebook for building user interfaces. It allows developers to create reusable UI components and efficiently manage the state of their applications. Here are some key aspects of ReactJS:


      

    Component-Based Architecture: ReactJS follows a component-based architecture, where the user interface is divided into small, reusable components. Components encapsulate their own logic, state, and rendering, making it easier to build and maintain complex user interfaces.


      Virtual DOM: ReactJS uses a virtual representation of the DOM (Document Object Model), known as the Virtual DOM. When the state of a component changes, React updates the Virtual DOM.


      JSX: JSX is a syntax extension for JavaScript used in React. It allows developers to write HTML-like code within JavaScript, making it easier to describe the structure and appearance of components. JSX code is transpiled to regular JavaScript using tools like Babel before being executed in the browser.

     

    Hooks: React introduced Hooks in version 16.8 as a way to use state and other React features in functional components. Hooks allow developers to write reusable logic and manage state within functional components without the need for class components. The most commonly used hooks are useState for managing state and useEffect for handling side effects such as fetching data or subscribing to events.



    React Router: React Router is a popular routing library for React applications. It enables developers to create single-page applications with multiple views and handles routing between different components based on the URL.


    State Management: React provides a flexible ecosystem of state management solutions. While React's built-in state management (useState ) is suitable for managing local component state, more complex applications may benefit from additional state management libraries like Redux. These libraries help manage global application state and provide predictable ways to update and access the state.



    ReactJS has gained widespread popularity due to its performance, reusability, and declarative approach to building user interfaces. It has large community. 



    NOTE - Here we will Tailwind CSS for designing.



     Here we first make a file as called Emoji.jsx.



    To validate an emoji in an input box using useFormik in ReactJS, you can utilize a custom validation function. Here's an example of how you can implement it:



    1) Install the emoji-regex library by running the following command in your project directory:



        npm install emoji-regex


         image  emoji-regex






        npm install formik


       




    2) Import the necessary dependencies in your component:



    import { useFormik } from 'formik';
    import emojiRegex from 'emoji-regex/RGI_Emoji';
    


    3) Define the validation function to check if the input contains any emoji:



    const validateEmoji = (value) => {
      if (emojiRegex().test(value)) {
        return 'Emojis are not allowed.';
      }
    };
    



    4) Use useFormik hook to manage your form and add the validate property to the input field you want to validate:




    const MyForm = () =&gt {
        const formik = useFormik({
          initialValues: {
            myInput: '',
          },
          onSubmit: (values) =&gt {
            // Handle form submission
          },
        });
      
        return (
          &ltform onSubmit={formik.handleSubmit}&gt
            &ltinput
              id="myInput"
              name="myInput"
              type="text"
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              value={formik.values.myInput}
              // Add the validation function to validate the input field
              validate={validateEmoji}
            /&gt
            {formik.errors.myInput && formik.touched.myInput && (
              &ltdiv&gt{formik.errors.myInput}&lt/div&gt
            )}
            &ltbutton type="submit"&gtSubmit&lt/button&gt
          &lt/form&gt
        );
      };
      



    Use useFormik hook to manage your form and add the validate property to the input field you want to validate:Note the validate={validateEmoji} prop added to the input field, which references the custom validation function.



    5) Finally, render the MyForm component wherever you need it in your application:

      


    const App = () =&gt {
        return &ltMyForm />
      };
      
      export default App;
    




    With this setup, the validateEmoji function will be called whenever the input field value changes or the input loses focus. If an emoji is found in the input, the validation function will return an error message, and the error will be displayed below the input field.



      Remember to adjust the code based on your specific use case and form structure.


    Full Code




    import React, { useState } from 'react';
    import { useFormik } from 'formik';
    // import emojiRegex from 'emoji-regex/RGI_Emoji';
    import emojiRegex from 'emoji-regex';
    
    
    function Emoji() {
     
      const [data, setData] = useState(null);
    
      const validateEmoji = (value) =&gt {
        if (emojiRegex().test(value)) {
          return 'Emojis are not allowed.';
        }
      };2
    
    const formik = useFormik({
      initialValues: {
        myInput: '',
      },
    });
    
    function getData (val) {
      console.log(val.target.value);
      setData(val.target.value);
    }
    
      return (
        &ltdiv&gt
          &ltdiv className=" grid  grid-cols-1 lg:grid-cols-1  md:grid-cols-1 sm:grid-cols-1  "&gt
            &ltdiv className="h-auto md:grid-cols-6 ml-36   text-center md:grid-rows-6"&gt
              &ltdiv className="mx-auto mt-36   w-80"&gt
                &ltform className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"  onSubmit={formik.handleSubmit}&gt
                  &ltdiv className="mb-1"&gt
                    &ltinput
                      
                      className="shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
                      id="myInput"
            name="myInput"
            type="text"
            onChange={getData}
            onBlur={formik.handleBlur}
            value={formik.values.myInput}
            // Add the validation function to validate the input field
            validate={validateEmoji}
                    /&gt
                    {formik.errors.myInput && formik.touched.myInput && (
                      &ltdiv&gt{formik.errors.myInput}&lt/div&gt
                    )}
                  &lt/div&gt  
                &lt/form&gt
                {data}
              &lt/div&gt
            &lt/div&gt
          &lt/div&gt
        &lt/div&gt
      );
    }
    
    export default Emoji;
    



    Output 





    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking. 


  • 0 comments:

    Post a Comment

    For Any Tech Updates, Hacking News, Internet, Computer, Technology and related to IT Field Articles Follow Our Blog.